package jman.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jman.mode.User;

public class UserDao {
	public User getUserById(int id) throws SQLException{
		User user=new User();
		Dao d=new Dao();
		d.start();
		String sql="select * from user where id="+id;
		ResultSet rs=d.read(sql);
		while(rs.next()){
			user=new User(id,rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
		}
		d.close();
		return user;
	}
	public boolean addUser(User user){
		boolean flag=false;
		Dao d=new Dao();
		d.start();
		String sql="insert into user (name,pwd,role) values ('"+user.getName()+"','"+user.getPwd()+"','"+user.getRole()+"')";
		flag=d.add(sql);
		d.close();
		return flag;
	}
	public User getUserWhenRegist(String name,String pwd,String role) throws SQLException{
		User user=new User();
		Dao d=new Dao();
		d.start();
		String sql="select * from user where name='"+name+"' and pwd='"+pwd+"' and role='"+role+"' order by modifytime desc limit 1";
		ResultSet rs=d.read(sql);
		while(rs.next()){
			user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
		}
		d.close();
		return user;
	}
	public String getNameById(int id) throws SQLException{
		String name="";
		Dao d=new Dao();
		d.start();
		String sql="select * from user where id="+id;
		ResultSet rs=d.read(sql);
		while(rs.next()){
			name=rs.getString(2);
		}
		d.close();
		return name;
	}
	public List<User> getUserListAll() throws SQLException{
		List<User> userList=new ArrayList<User>();
		Dao d=new Dao();
		d.start();
		String sql="select * from user";
		ResultSet rs=d.read(sql);
		while(rs.next()){
			User user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
			userList.add(user);
		}
		d.close();
		return userList;
	}
	public List<User> getStudentsListAll() throws SQLException{
		List<User> userList=new ArrayList<User>();
		Dao d=new Dao();
		d.start();
		String sql="select * from user where role='学生'";
		ResultSet rs=d.read(sql);
		while(rs.next()){
			User user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
			userList.add(user);
		}
		d.close();
		return userList;
	}
	public List<User> getUserListByVote_Id(int vote_Id) throws SQLException{
		List<User> userList=new ArrayList<User>();
		Dao d=new Dao();
		d.start();
		String sql="select * from user where id in(select user_id from vote_user1 where vote_id="+vote_Id+")";
		ResultSet rs=d.read(sql);
		while(rs.next()){
			User user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
			userList.add(user);
		}
		d.close();
		return userList;
	}
}
